<!--推文管理-知识广告 -->
<template>
  <div class="k-list pad">
    <div class="head">
      <span>知识广告</span>
    </div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="openAddDialog"
    >添加跳转小程序广告</el-button>
    <el-table :data="adList" stripe border class="m-t-b">
      <el-table-column label="广告跳转类型">
        <template slot-scope="scope">
          {{(!scope.row.type || scope.row.type == 1) ? '文章' : '微信小程序'}}
        </template>
      </el-table-column>
      <el-table-column label="广告标题" prop="title"></el-table-column>
      <el-table-column label="广告图片">
        <template slot-scope="scope">
          <img :src="scope.row.advertisementPic" style="width: 200px;" />
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">
          {{(!scope.row.type || scope.row.type == 1) ? (scope.row.knowledgeType == '0' ? '文章' : '视频') : ''}}
        </template>
      </el-table-column>
      <el-table-column label="浏览量">
        <template slot-scope="scope">
          {{(!scope.row.type || scope.row.type == 1) ? scope.row.browse : ''}}
        </template>
      </el-table-column>
      <el-table-column label="点赞数">
        <template slot-scope="scope">
          {{(!scope.row.type || scope.row.type == 1) ? scope.row.collection : ''}}
        </template>
      </el-table-column>
      <el-table-column label="appId">
        <template slot-scope="scope">
          {{(!scope.row.type || scope.row.type == 1) ? '' : scope.row.appId}}
        </template>
      </el-table-column>
      <el-table-column label="路径">
        <template slot-scope="scope">
          {{(!scope.row.type || scope.row.type == 1) ? '' : scope.row.path}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createDate"></el-table-column>
      <el-table-column label="是否启用">
        <template slot-scope="scope">
          <el-switch
            active-text="启用"
            inactive-text="禁用"
            v-model="scope.row.enable"
            @change="changeStatus($event, scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" @click="lookDetail(scope.row)">查看{{scope.row.knowledgeType == '0' ? '文章' : '视频'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="文章详情" :visible.sync="showArticle" width="50%">
      <div
        style="text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 10px;">
        {{articleTitle.title}}
      </div>
      <el-input v-model="currentArticle.knowledgeDesc" style="line-height: 20px;" type="textarea" rows="30" disabled></el-input>

      <div slot="footer">
        <el-button type="primary" @click="showArticle = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="视频详情"
      :visible.sync="showVideo"
    >
      <div
        style="text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 10px;"
      >
        {{articleTitle.title}}
      </div>
      <video
       width="100%"
       :src="currentVideo.knowledgeVideo"
       autoplay
       controls>
      </video>

      <div slot="footer">
        <el-button type="primary" @click="showVideo = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showDialog" title="添加跳转小程序广告">
      <el-form :model="ad" label-position="top" :rules="rules" ref="ad">
        <el-form-item label="appid" prop="appId">
          <el-input
            placeholder="要跳转的微信小程序的appid"
            v-model="ad.appId"
          />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input
            placeholder="需要跳转的页面路径(不填则默认跳转至首页)"
            v-model="ad.path"
          />
        </el-form-item>
        <el-form-item label="广告图片" prop="advertisementPic">
          <el-upload
            class="avatar-uploader"
            action="https://domain.com/placeholder"
            :show-file-list="false"
            :http-request="uploadArticleBanner"
            v-loading="isUploading"
          >
            <img
              v-if="ad.advertisementPic"
              :src="ad.advertisementPic"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        @click="confirmSave"
        :loading="loading"
      >保存</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { TimeSelect } from 'element-ui';
  import {
    getAdList,
    changeAdStatus,
    getArticleInfo,
    createAd
  } from '../api/version2';
  import {formatDate} from '../util'
  import { client } from '../util/oss';
  export default {
    name: 'adList',
    data() {
      return {
        adList: [],
        currentArticle: {},
        currentVideo: {},
        articleTitle: {},
        videoTitle: {},
        showArticle: false,
        showVideo: false,
        showDialog: false,
        loading: false,
        isUploading: false,
        ad: {
          appId: '',
          path: '',
          advertisementPic: '',
        },
        rules: {
          appId: [
            { required: true, message: 'appId不能为空', trigger: 'blur' }
          ],
          advertisementPic: [
            { required: true, message: '广告图片不能为空', trigger: 'blur' }
          ]
        }

      }
    },
    methods: {
      // 查询广告列表
      fetchAdList() {
        getAdList().then(res => {
          // console.log(res);
          let list = res.data.data || [];
          list.forEach(item => {
            item.createDate = formatDate(item.createDate, 'ZH');
            item.enable = Boolean(item.advertisementStatus)
          });
          this.adList = list
          // console.log(this.adList);
        }).catch( e => {

        })
      },
      openAddDialog () {
        this.ad.appId = '';
        this.ad.path = '';
        this.showDialog = true
      },
      confirmSave () { // 确认保存
        const that = this;
        this.$refs.ad.validate(valid => {
          if (valid) {
            that.loading = true;
            createAd({
              ...that.ad,
              type: 2
            })
            .then(res => {
              that.$message.success('创建成功');
              that.loading =false;
              that.showDialog = false;
              that.fetchAdList()
            })
            .catch(e => {
              that.loading = false
            })
          } else {
            return false
          }
        })
      },
      uploadArticleBanner ({ file }) { // 上传图片
        if (file.type.indexOf('image') === -1) {
          return this.$message.error('只能上传图片')
        };
        this.isUploading = true;
        let name = `DUDU${Date.now()}${Math.floor(Math.random() * 1000)}`;
        client.put(name, file)
        .then(res => {
          let url = res.url;
          url = url.replace('http:', 'https:');
          this.ad.advertisementPic = url;
          this.isUploading = false
        })
        .catch(e => {
          this.isUploading = false;
          this.$message.error('上传错误')
        })
      },
      changeStatus (e, row) { // 切换状态
      this.$confirm(`确定 ${e ? '启用' : '禁用'} 该广告吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        changeAdStatus({
          advertisementId: row.advertisementId,
          advertisementStatus: Number(e)
        })
        .then(res => {
          this.$message.success('操作成功');
          this.fetchAdList()
        })
        .catch(e => {})
      })
      .catch(err => {
        row.enable = !e
      })
    },

    // 查看文章/视频详情
    lookDetail(row) {
      console.log(row);
      getArticleInfo(row.knowledgeId)
        .then(res => {
        if(row.knowledgeType == '0') { //文章
          this.articleTitle = row;
          this.showArticle = true;
          this.currentArticle = res.data.data;
          // console.log(this.currentArticle);
        } else if(row.knowledgeType == '1') { //文章
          this.videoTitle = row;
          this.currentVideo = true;
          this.currentVideo = res.data.data;
        }
      }).catch(err => {
        console.log(err);
      });
    }

    },
    created() {
      this.fetchAdList();
    }
  }
</script>
